//
//  LoginViewController.m
//  Exam16-2
//
//  Created by 孙晓晔 on 2017/5/30.
//  Copyright © 2017年 孙晓晔. All rights reserved.
//

#import "LoginViewController.h"
#import "ChatViewController.h"
#import "ApplyViewController.h"

@interface LoginViewController ()
@property (weak, nonatomic) IBOutlet UITextField *username; // 帐号
@property (weak, nonatomic) IBOutlet UITextField *password; // 密码
@property (weak, nonatomic) IBOutlet UIButton *regBtn; // 注册
@property (weak, nonatomic) IBOutlet UIButton *loginBtn; // 登录

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSNotificationCenter *notify = [NSNotificationCenter defaultCenter];
    [notify addObserver:self selector:@selector(onChange) name:UITextFieldTextDidChangeNotification object:self.username];
    [notify addObserver:self selector:@selector(onChange) name:UITextFieldTextDidChangeNotification object:self.password];
    
    [self onChange];
    
    EMOptions *options = [EMOptions optionsWithAppkey:@"easemob-demo#chatdemoui"];
    
    options.apnsCertName = @"chatdemo-dev";
    
    EMError *error = [[EMClient sharedClient] initializeSDKWithOptions:options];
    
    if (!error) {
        NSLog(@"初始化成功");
    }
    
}

-(void)dealloc {
    NSNotificationCenter *notify = [NSNotificationCenter defaultCenter];
    [notify removeObserver:self name:UITextFieldTextDidChangeNotification object:self.username];
    [notify removeObserver:self name:UITextFieldTextDidChangeNotification object:self.password];
}

// 输入框检测
-(void)onChange {
    if (self.username.text.length > 0
        && self.password.text.length > 0) {
        self.regBtn.enabled = TRUE;
        self.loginBtn.enabled = TRUE;

    } else {
        self.regBtn.enabled = FALSE;
        self.loginBtn.enabled = FALSE;
    }
}

// 注册
- (IBAction)doRegister:(UIButton *)sender {
    NSLog(@"注册");
    
    //隐藏键盘
    [self.view endEditing:YES];
    
    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMError *error = [[EMClient sharedClient] registerWithUsername:weakself.username.text password:weakself.password.text];
        if (error) {
            NSLog(@"注册失败，%@", error);
        } else {
            NSLog(@"注册成功", nil);
        }
    });
}

// 登录
- (IBAction)doLogin:(UIButton *)sender {
    
    EMError *error = [[EMClient sharedClient] loginWithUsername:self.username.text password:self.password.text];
    
    if (!error) {
        NSLog(@"登录成功");
        
        [[ApplyViewController shareController] loadDataSourceFromLocalDB];
        
        [self performSegueWithIdentifier:@"login2chat" sender:nil];
        
    } else {
        NSLog(@"登录失败");
    }
}

@end
